import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { Strategy } from 'passport-local'
import { AuthService } from '../auth.service'
import { AuthUser } from '../interfaces/jwt-payload.interface'

/**
 * 本地认证策略
 * 用于用户名密码登录验证
 */
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'username', // 可以是用户名或邮箱
      passwordField: 'password'
    })
  }

  /**
   * 验证用户凭据
   * @param username 用户名或邮箱
   * @param password 密码
   * @returns 认证用户信息
   */
  async validate(username: string, password: string): Promise<AuthUser> {
    try {
      const user = await this.authService.validateUser(username, password)

      if (!user) {
        throw new UnauthorizedException('用户名或密码错误')
      }

      return {
        ...user,
        role: user.role as any, // 临时类型转换
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      }
    } catch (error) {
      if (error instanceof UnauthorizedException) {
        throw error
      }
      throw new UnauthorizedException('登录验证失败')
    }
  }
}
